#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "strings.h"

char * strip_quotes(char * str)
{
  if (*str == '"')
    str++;
  int last_index = strlen(str) -1;
  if (str[last_index] == '"')
    str[last_index] = 0;
  return str;
}

char * trim(char * str) 
{
  while (*str != 0 && *str == ' ')
    str++;
  return str;
}


char * *  init_tokens(int ntokens, int max_token_length)
{
  char * * result = malloc(sizeof(char *) * ntokens);
  int i = 0;
  for (i = 0; i < ntokens; i++)
    result[i] = malloc(max_token_length * sizeof(char*));
  return result;
}

void free_tokens(char * * tokens, int n) 
{
  int i = 0;
  for (i = 0; i < n; i++) {
    free(tokens[i]);
  }
  free(tokens);
}


void split(char * string, char character, char * * tokens) 
{
  int i = 0;
  char * current = string;
  char * next = 0;

  do {
    next = strchr(current, character);
    if (next != 0) {
      *next = 0;
      strcpy(tokens[i++], current);
      current = next+1;
    }
  } while (next != 0);
  strcpy(tokens[i++], current);
  tokens[i] = 0;
}


void strip_newlines(char * str)
{
  while (str[strlen(str)-1] == '\n' || str[strlen(str)-1] == '\r')
    str[strlen(str)-1] = 0;
}

int is_suffix(char * str, char a, char b, char c)
{
  int len = strlen(str);
  return len >= 3 && str[len-3] == a && str[len-2] == b && str[len-1] == c;
}

void get_mime_type_by_filename(char * filename, char * type)
{
  if (is_suffix(filename, 'p', 'd', 'f'))
    strcpy(type, "application/pdf");
  else if (is_suffix(filename, 'd', 'o', 'c'))
    strcpy(type, "application/msword");
  else 
    strcpy(type, "application/bin");
} 

